<!--
 * @页面名称:element表格1
 * @描述: 
 * @作者: 
 * @Date:
-->
<template>
  <div class="main-box">
    <splitpanes :dbl-click-splitter="false" style="display: flex">
      <pane size="15">
        <TreeFilter
          label="Fonds_Name"
          title="部门列表(单选)"
          :data="treeFilterData"
          :default-value="initParam.departmentId"
          :multiple="false"
          id="Fonds_ID"
          @change="changeTreeFilter"
        />
      </pane>
      <pane size="85">
        <div class="table-box">
          <ProTable
            ref="proTable"
            title="用户列表"
            row-key="Dept_ID"
            :indent="30"
            :columns="columns"
            :request-api="getTable"
            :request-auto="false"
            :init-param="initParam"
            :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
            @rowClick="rowClick"
            @selection-change="selectionChange"
          >
            <!-- 表格 header 按钮 -->
            <template #tableHeader>
              <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')">新增用户</el-button>
              <el-button type="primary" :disabled="uploadDisabled" :icon="Upload" plain @click="uploadFile">上传文件</el-button>
              <el-button type="primary" :disabled="downloadDisabled" :icon="Download" plain @click="download">前端导出</el-button>
              <el-button type="primary" :disabled="downloadDisabled2" :icon="Download" plain @click="download2">导出</el-button>
            </template>
            <!-- 表格操作 -->
            <template #operation="scope">
              <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看全文</el-button>
              <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
              <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
            </template>
          </ProTable>
        </div>
      </pane>
    </splitpanes>
    <!-- 新增弹框 -->
    <el-dialog v-model="dialogSetting.visible" :title="dialogSetting.title" width="30%" draggable>
      <el-form label-width="90px" :model="formData" :rules="rules" ref="formRef">
        <el-form-item label="顺序号:" prop="dept_Order">
          <el-input v-model="formData.dept_Order"></el-input>
        </el-form-item>
        <el-form-item label="部门名称1:" prop="dept_Name">
          <el-input v-model="formData.dept_Name"></el-input>
        </el-form-item>
        <el-form-item label="部门名称2:" prop="dept_Name2">
          <el-input v-model="formData.dept_Name2"></el-input>
        </el-form-item>
        <el-form-item label="部门名称3:" prop="dept_Name3">
          <el-input v-model="formData.dept_Name3"></el-input>
        </el-form-item>
        <el-form-item label="部门代号1:" prop="dept_Code">
          <el-input v-model="formData.dept_Code"></el-input>
        </el-form-item>
        <el-form-item label="部门代号2:" prop="dept_Code2">
          <el-input v-model="formData.dept_Code2"></el-input>
        </el-form-item>
        <el-form-item label="部门代号3:" prop="dept_Code3">
          <el-input v-model="formData.dept_Code3"></el-input>
        </el-form-item>
        <el-form-item label="父级:" prop="dept_Father">
          <el-tree-select
            style="width: 100%"
            check-strictly
            v-model="formData.dept_Father"
            node-key="Dept_ID"
            :props="{ label: 'Dept_Name', children: 'children' }"
            :data="parentData"
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="是否启用:" prop="dept_Enable">
          <el-checkbox v-model="formData.dept_Enable"></el-checkbox>
        </el-form-item>
        <el-form-item label="备注:" prop="dept_Remark">
          <el-input v-model="formData.dept_Remark"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogSetting.visible = false">取消</el-button>
          <el-button type="primary" @click="handle"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 全文弹框 -->
    <el-dialog
      class="fulltextDialog"
      v-model="dialogSetting2.visible"
      :title="dialogSetting2.title"
      width="45%"
      draggable
      height="500"
    >
      <ProTable
        ref="proTable2"
        title="全文列表"
        row-key="Dept_ID"
        :indent="30"
        :columns="columns2"
        :request-api="getTable"
        :request-auto="false"
        :pagination="false"
        :init-param="initParam2"
        :toolButton="false"
      >
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">打开</el-button>
          <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
        </template>
      </ProTable>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogSetting.visible = false">取消</el-button>
          <el-button type="primary" @click="dialogSetting.visible = false"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 上传文件 -->
    <input ref="upload" type="file" @change="uploadFileChange" style="display: none" />
    <!-- 文件上传进度条 -->
    <el-dialog
      title="正在上传文件...请稍等"
      v-model="fulltextModal.isShow"
      width="30%"
      class="progress-modal"
      top="300px"
      center
      :close-on-click-modal="false"
      :showClose="false"
    >
      <template #footer>
        <span class="dialog-footer">
          <el-progress :text-inside="true" :stroke-width="20" :percentage="fulltextModal.percent" status="success" />
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="treeProTable">
import { onMounted, reactive, ref } from "vue";
import ProTable from "@/components/ProTable/index.vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { CirclePlus, Delete, EditPen, View, Upload, Download } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import { useHandleData } from "@/hooks/useHandleData";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { transTree } from "@/utils/util";
import dtime from "moment";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";

const { proxy } = useCurrentInstance();
// tree数据
const treeFilterData = ref<any>([]);
// tree点击保存节点
const treeClickObj: any = ref({});
// 上传全文按钮配置
const uploadDisabled = ref(true);
// 上传弹出框实例
const upload = ref();
// 前端导出按钮配置
const downloadDisabled = ref(true);
// 导出按钮配置
const downloadDisabled2 = ref(true);
// 全文数据
const fulltextData = ref<any[]>([]);
// 弹出框配置参数
const dialogSetting = reactive({
  visible: false,
  title: ""
});
// 全文弹出框配置参数
const dialogSetting2 = reactive({
  visible: false,
  title: ""
});
// 上传文件进度条配置
const fulltextModal = reactive({
  isShow: false,
  percent: 0
});
// 表格配置列
const columns: any[] = reactive([
  { type: "selection" },
  { prop: "Dept_Order", label: "顺序号" },
  { prop: "Dept_Name", label: "部门名称", search: { el: "input" } },
  { prop: "Dept_Name2", label: "部门名称2" },
  { prop: "Dept_Name3", label: "部门名称3" },
  { prop: "Dept_Code", label: "部门代号" },
  { prop: "Dept_Code2", label: "部门代号2" },
  { prop: "Dept_Code3", label: "部门代号3" },
  {
    prop: "Dept_Enable",
    label: "是否启用",
    tag: true,
    render: (scope: any) => {
      return <el-tag type={scope.row.Dept_Enable ? "success" : "danger"}>{scope.row.Dept_Enable ? "启用" : "禁用"}</el-tag>;
    }
  },
  { prop: "Dept_Remark", label: "备注" },
  { prop: "operation", label: "操作", width: 300, fixed: "right" }
]);
// 全文表格配置列
const columns2: any[] = reactive([
  { prop: "AI_Index", label: "序号", width: 80 },
  { prop: "AI_Name", label: "文件名" },
  { prop: "AI_Source_Extension", label: "文件类型", width: 150 },
  { prop: "AI_Source_Size", label: "文件大小", width: 100 },
  { prop: "AI_UploadDateTime", label: "上传时间", width: 150 },
  { prop: "AI_FileDateTime", label: "创建时间", width: 150 },
  { prop: "operation", label: "操作", width: 200, fixed: "right" }
]);
// 初始化请求参数
const initParam = reactive({ departmentId: "" });
// 全文初始化请求参数
const initParam2 = reactive({ departmentId: "" });
// 获取 ProTable 元素
const proTable = ref();
// 表单配置
const formData = reactive({
  dept_Code: "",
  dept_Code2: "",
  dept_Code3: "",
  dept_Name: "",
  dept_Name2: "",
  dept_Name3: "",
  dept_Enable: true,
  dept_Father: null as any,
  dept_Order: 1,
  dept_Remark: ""
});
// 表单规则
const rules = reactive<FormRules>({});
// 表单实例
const formRef = ref<FormInstance>();
// 弹出框表单父级数据
const parentData = ref<any[]>([]);
// 表格多选数据
const selectionData = ref([]);
// 获取树数据
const getTree = () => {
  proxy.$vueAxios.get("MasterBaseFonds/GetFondsTree").then((res: any) => {
    treeFilterData.value = transTree(res.List, "Fonds_ID", "Fonds_Father");
  });
};
// 树形筛选切换
const changeTreeFilter = (node: any) => {
  treeClickObj.value = node;
  proTable.value.pageable.pageIndex = 1;
  initParam.departmentId = node.Fonds_ID;
};
// 获取表格数据
const getTable = (params: any) => {
  return proxy.$vueAxios.post("Master_Base_Dept/GetConditional", {
    ...params,
    order: "Dept_Order asc",
    dtoList: [{ fieldName: "Fonds_ID", fieldValue: treeClickObj.value.Fonds_ID, conditionalType: 0 }]
  });
};
// 单击表格
const rowClick = (row: any) => {
  uploadDisabled.value = false;
};
// 多选
const selectionChange = (rowArr: any) => {
  selectionData.value = rowArr;
  if (selectionData.value.length > 0) {
    downloadDisabled.value = false;
    downloadDisabled2.value = false;
  } else {
    downloadDisabled2.value = true;
    downloadDisabled.value = true;
  }
};
// 新增/修改/查看按钮事件
const openDrawer = (title: string, row: any = {}) => {
  switch (title) {
    case "新增":
      dialogSetting.visible = true;
      dialogSetting.title = "新增";
      formRef.value?.resetFields();
      break;
    case "编辑":
      dialogSetting.visible = true;
      dialogSetting.title = "编辑";
      break;
    case "查看":
      dialogSetting2.visible = true;
      dialogSetting2.title = "查看全文";
  }
};
// 删除事件
const deleteAccount = async (row: any = {}) => {
  await useHandleData(deleteData, { id: [row.Dept_ID] }, `删除该条数据`);
  proTable.value.getTableList();
};
// 删除接口
const deleteData = (params: { id: string[] }) => {
  return proxy.$vueAxios.post("Master_Base_Dept/Delete", params.id);
};
// 上传文件
const uploadFile = () => {
  upload.value.click();
};
const uploadFileChange = async () => {
  const files = upload.value.files;
  const filesLength = files.length;
  fulltextModal.percent = 0;
  let arrList = [...fulltextData.value];
  const maxIndex =
    fulltextData.value.length > 0
      ? Math.max.apply(
          Math,
          fulltextData.value.map(item => {
            return item.AI_Index;
          })
        )
      : 0;
  let fileCount = 0;
  let bytesPerPiece = 1024 * 1024 * 10; // 每个文件切片大小定为10MB
  let totalPieces;
  for (let i = 0; i < files.length; i++) {
    const lastFileTime = dtime(files[i].lastModified).format("YYYY-MM-DD HH:mm:ss");
    let blob = files[i];
    let start = 0;
    let end;
    let progressIndex = 1;
    let filesize = blob.size;
    // 计算文件切片总数
    totalPieces = Math.ceil(filesize / bytesPerPiece);
    const AIID = proxy.$global.createID();
    for (let uploadIndex = 1; uploadIndex <= totalPieces; uploadIndex++) {
      end = Math.min(filesize, start + bytesPerPiece);
      let chunk = blob.slice(start, end); // 切割文件
      const resultObj: any = {};
      const fileData: any = new FormData();
      fileData.append("file", chunk);
      fileData.append("AI_ID", AIID);
      fileData.append("PieceTotal", totalPieces as any);
      fileData.append("PieceNow", uploadIndex);
      fileData.append("AI_Name", blob.name);
      fileData.append("AI_FileDateTime", lastFileTime);
      fileData.append("AI_Size", filesize);
      fileData.append("AI_Index", Number(maxIndex) + 1 + i);
      // fileData.append("FM_ID", fatherObj.value.FM_ID);
      // fileData.append("Record_ID", fatherObj.value.Record_ID);
      resultObj["AI_Index"] = Number(maxIndex) + 1 + i;
      resultObj["AI_Name"] = blob.name;
      resultObj["AI_Size"] = blob.size;
      resultObj["AI_ID"] = AIID;
      resultObj["AI_FileDateTime"] = lastFileTime;
      fulltextModal.isShow = true;
      const Res = await proxy.$vueAxios.post("MasterBaseAllInfos/Upload/Piece", fileData, { noLoading: true });
      if (!Res.Mark) {
        proxy.$warning({
          title: "提示",
          content: Res.Msg
        });
        fulltextModal.isShow = false;
        break;
      }
      start = start + chunk.size;
      fulltextModal.percent = Math.round((progressIndex / totalPieces / filesLength) * 100);
      progressIndex++;
      // 单个文件传输完成
      if (uploadIndex >= totalPieces) {
        arrList = [...arrList, resultObj];
        fulltextData.value = arrList;
        fileCount++;
      }
      // 所有文件传输完成
      if (fileCount >= filesLength) {
        fulltextModal.isShow = false;
      }
    }
  }
  upload.value.value = "";
};
// 新增/修改确认事件
const handle = () => {};
// 前端导出
const download = () => {
  if (selectionData.value.length === 0) {
    proxy.$notify.warning({
      title: "提示",
      message: "未选中任何数据!"
    });
    return false;
  }
  const header = columns.filter(v => v.label).map(v => v.label);
  const filterVal = columns.filter(v => v.prop).map(v => v.prop);
  const data = selectionData.value.map((v: any) => filterVal.map((j: any) => v[j]));
  import("@/vendor/Export2Excel").then(excel => {
    excel.export_json_to_excel({
      header: header, //表头 必填
      data, //具体数据 必填
      filename: "基础表格", //非必填
      autoWidth: true, //非必填
      bookType: "xlsx" //非必填
    });
  });
};
// 导出
const download2 = () => {};
onMounted(() => {
  getTree();
});
</script>
<style lang="scss" scoped>
:deep(.fulltextDialog) {
  .el-dialog__body {
    height: 450px;
  }
}
.filter {
  height: 100%;
  width: 100%;
  overflow: auto !important;
}
.table-box {
  width: 100%;
  :deep(.table-search) {
    margin-bottom: 5px;
  }
}
</style>
